package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.database.entity.ArenaGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.parser.FightArenaXmlParser
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.utils.TimeUtils
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 竞技场工作
class PenguinArenaWork(
    private val config: ArenaGameConfigEntity,
    uin: String
): BaseWork(uin) {
    
    private val gameApi = GameApi.getInstance()
    private val phoneGameApi = PhoneGameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override val name: String
        get() = "竞技场"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询竞技场信息
            val queryResult = gameApi.queryArenaInfo()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    var hasChallenged = false
                    
                    // 检查是否可以挑战：下个赛季时间为-1且剩余次数大于0
                    if (response.nextSeasonTime == -1 && response.leftFreeTimes > 0) {
                        // 直接挑战
                        hasChallenged = executeChallengeLoop(response.leftFreeTimes)
                    }
                    
                    // 如果有发生挑战，重新查询竞技场信息
                    val finalArenaInfo = if (hasChallenged) {
                        val requeryResult = gameApi.queryArenaInfo()
                        requeryResult.getOrElse { response }
                    } else {
                        response
                    }
                    
                    // 检查并领取奖励
                    executeClaimRewards(finalArenaInfo)
                    
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    
    /**
     * 执行挑战循环，根据剩余次数挑战
     * @param remainingTimes 剩余挑战次数
     * @return 是否有发生挑战
     */
    private suspend fun executeChallengeLoop(remainingTimes: Int): Boolean {
        if (remainingTimes <= 0) {
            return false
        }
        
        var hasChallenged = false
        
        // 根据剩余次数循环挑战
        repeat(remainingTimes) { index ->
            val challengeResult = phoneGameApi.arenaChallenge()
            challengeResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.actionResult)
                    hasChallenged = true
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    hasChallenged = true
                }
            )
        }
        
        return hasChallenged
    }
    
    /**
     * 执行奖励领取
     */
    private suspend fun executeClaimRewards(arenaInfo: com.promise.jokerdream.response.pc.QueryArenaInfoPCResponse) {
        // 领取每日奖励
        if (arenaInfo.canDrawDailyReward > 0) {
            val dailyRewardResult = gameApi.claimArenaDailyReward()
            dailyRewardResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }
        
        // 领取段位奖励
        if (arenaInfo.canDrawRankReward > 0) {
            val rankRewardResult = gameApi.claimArenaRankReward()
            rankRewardResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
        }
    }
}